from classpath import entry
from classpath import entry_zip
from classpath import entry_composite
import os


class ClassPath(entry.IEntry):
    bootClasspath = entry.IEntry()
    extClasspath = entry.IEntry()
    userClasspath = entry.IEntry()

    def getJreDir(self, jreOption):
        if jreOption != "" and exit(jreOption):
            return jreOption
        if os.path.exists("./jre"):
            return "./jre"
        raise Exception("Can not find jre folder!")

    def parseUserClasspath(self, cpOption):
        if cpOption == "":
            cpOption = "."
        self.userClasspath = self.newWildcardEntry(cpOption)

    def parseBootAndExtClasspath(self, jreOption):
        jreDir = self.getJreDir(jreOption)
        jreLibPath = jreDir+"/lib"
        self.bootClasspath = self.newWildcardEntry(jreLibPath)
        jreExtPath = jreLibPath+"/ext"
        self.extClasspath = self.newWildcardEntry(jreExtPath)
        # print(self.bootClasspath.readClass("sun/nio/cs/ext/Big5"))
        # print(self.bootClassPath.readClass("sun/nio/cs/ext/Big5"))
        # print(self.extClasspath)

    def newWildcardEntry(self, path):
        composite = entry_composite.CompositeEntry()
        root = path
        #print("path==%s" % path)
        for f in os.listdir(path):
            if f.endswith(".jar") or f.endswith(".JAR"):
                zipEntry = entry_zip.ZipEntry(os.path.join(root, f))
                composite.append(zipEntry)
                # print(zipEntry.readClass("sun/nio/cs/ext/Big5"))
                print(os.path.join(root, f))
       # print(composite.readClass("sun/nio/cs/ext/Big5"))
        return composite

    def readClass(self, className):
        realClassName = className+'.class'
        data = self.bootClasspath.readClass(realClassName)
        if data != None:
            return data
        data = self.extClasspath.readClass(realClassName)
        if data != None:
            return data
        data = self.userClasspath.readClass(realClassName)
        if data != None:
            return data
        raise Exception(className,'class not find!')

    def String(self):
        strs = []
        str = '-'
        strs.append(self.bootClasspath.String())
        strs.append(self.extClasspath.String())
        strs.append(self.userClasspath.String())

        return str.join(strs)


def Parse(jreOption, cpOption):
    cp = ClassPath()
    cp.parseBootAndExtClasspath(jreOption)
    cp.parseUserClasspath(cpOption)
    return cp
